//
//  ST_InteractiveST_PeculiarityGroupViewController.swift
//  btvideo
//
//  Created by mac on 2020/6/1.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import HandyJSON
import SnapKit
import SwiftyUserDefaults


/**
 可交互的 组详情
 */
class ST_InteractiveST_PeculiarityGroupViewController: ST_PeculiarityGroupViewController,ST_PairsPresenAnimatorProtocol {

    
    static func present_interactive_peculiarity_group_controller(accid:String,groupId:String,peculiarity_id:String,remark:String,firstPhotoSize:CGSize,transition:ST_PairsTransition,presentRootController:UIViewController){
        
        
        let vc = ST_InteractiveST_PeculiarityGroupViewController.init(accid: accid, groupId: groupId, peculiarity_id: peculiarity_id, firstPhotoSize: firstPhotoSize,remark:remark)
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.transitioningDelegate = transition
        
        nav.modalPresentationStyle = .custom
        
        presentRootController.present(nav, animated: true, completion: nil)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setup_dismiss_gesture()
    }
    
//    MARK: - override Proeprties
    private lazy var _headerView:ST_PeculiarityGroupHeaderView = {
        
        let control = ST_PeculiarityGroupHeaderView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: header_height))
        
        control.phDelegate = self
        
        return control
    }()
    
    override var headerView: ST_PeculiarityGroupHeaderView{
        get { return _headerView }
        set { _headerView = newValue }
    }
    
    
    
    //    MARK: - Dismissal Gesture
    
    fileprivate var dragging_down_to_dismiss = false
    
    final class ST_DismissalPanGesture: UIPanGestureRecognizer {}
    final class ST_DismissalScreenEdgePanGesture: UIScreenEdgePanGestureRecognizer {}
    
    private lazy var dismissalPanGesture: ST_DismissalPanGesture = {
        let pan = ST_DismissalPanGesture()
        pan.maximumNumberOfTouches = 1
        return pan
    }()
    
    private lazy var dismissal_screen_edge_pan_gesture: ST_DismissalScreenEdgePanGesture = {
        let pan = ST_DismissalScreenEdgePanGesture()
        pan.edges = .left
        return pan
    }()
    
    fileprivate var interactive_starting_point: CGPoint?
    fileprivate var dismissal_animator: UIViewPropertyAnimator?
    

    fileprivate func setup_dismiss_gesture(){
        
        dismissalPanGesture.addTarget(self, action: #selector(handleDismissalPan(gesture:)))
        dismissalPanGesture.delegate = self
        
        dismissal_screen_edge_pan_gesture.addTarget(self, action: #selector(handleDismissalPan(gesture:)))
        dismissal_screen_edge_pan_gesture.delegate = self
        
        // Make drag down/scroll pan gesture waits til screen edge pan to fail first to begin
        dismissalPanGesture.require(toFail: dismissal_screen_edge_pan_gesture)
        tableView.panGestureRecognizer.require(toFail: dismissal_screen_edge_pan_gesture)
        
        view.addGestureRecognizer(dismissalPanGesture)
        view.addGestureRecognizer(dismissal_screen_edge_pan_gesture)
        
    }
    
    
    func package_header_play_view(_ view:ST_PairsShareParticularView){
        
        
        view.cornerRadius = 0
        
        self.headerView.package_play_view(view)
        
        
        self.headerView.bind_model(self.headerModel)
        
    }
    
    
}




//MARK: - handle Dismissal Pan
extension ST_InteractiveST_PeculiarityGroupViewController:UIGestureRecognizerDelegate{
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        
        if dragging_down_to_dismiss || (scrollView.isTracking && scrollView.contentOffset.y < 0) {
            dragging_down_to_dismiss = true
            scrollView.contentOffset = .zero
        }
        
        scrollView.showsVerticalScrollIndicator = !dragging_down_to_dismiss
    }
    
    // This handles both screen edge and dragdown pan. As screen edge pan is a subclass of pan gesture, this input param works.
    @objc func handleDismissalPan(gesture: UIPanGestureRecognizer) {
        
        let isScreenEdgePan = gesture.isKind(of: ST_DismissalScreenEdgePanGesture.self)
        let canStartDragDownToDismissPan = !isScreenEdgePan && !dragging_down_to_dismiss
        
        // Don't do anything when it's not in the drag down mode
        if canStartDragDownToDismissPan {
            
//            print("当前不执行")
            
            return
        }
        
//        print("当前执行！！！")
        
        let targetAnimatedView = gesture.view!
        let startingPoint: CGPoint
        
        if let p = interactive_starting_point {
            startingPoint = p
        } else {
            // Initial location
            startingPoint = gesture.location(in: nil)
            interactive_starting_point = startingPoint
        }
        
        let currentLocation = gesture.location(in: nil)
        let progress = isScreenEdgePan ? (gesture.translation(in: targetAnimatedView).x / 100) : (currentLocation.y - startingPoint.y) / 100
        let targetShrinkScale: CGFloat = 0.7
        
        let orginalX = headerView.pairsHeader?.present_start_rect.origin.x ?? 0
        let orginalY = headerView.pairsHeader?.present_start_rect.origin.y ?? 0
        let orginalW = headerView.pairsHeader?.present_start_rect.width ?? 0
        
        let x = (0 - orginalX)*targetShrinkScale + orginalX
        let y = (statusBarHeight-orginalY)*targetShrinkScale + orginalY
        let w = (ScreenWidth - orginalW)*targetShrinkScale + orginalW
        let scaleX =  w/ScreenWidth
        
        let h = ScreenHeight/ScreenWidth*w
        //        let centerY = headerView.center.y
        let centerX = headerView.center.x
        
        let sTransform = CGAffineTransform.init(scaleX:scaleX, y: scaleX)
        let tr = CGAffineTransform.init(translationX: (x+w/2.0)-centerX, y: h/2.0+y-ScreenHeight/2.0)
        let t = sTransform.concatenating(tr)
        
        func createInteractiveDismissalAnimatorIfNeeded() -> UIViewPropertyAnimator {
            if let animator = dismissal_animator {
                return animator
            } else {
                let animator = UIViewPropertyAnimator(duration: 0, curve: .linear, animations: {
                    targetAnimatedView.transform = t
                })
                animator.isReversed = false
                animator.pauseAnimation()
                animator.fractionComplete = progress
                return animator
            }
        }
        
        switch gesture.state {
        case .began:
            dismissal_animator = createInteractiveDismissalAnimatorIfNeeded()
            
            shield_click_on_loading(isShield: true)
        case .changed:
            dismissal_animator = createInteractiveDismissalAnimatorIfNeeded()
            
            let actualProgress = progress
            
//            print("actualProgress:",actualProgress)
            
            let isDismissalSuccess = actualProgress >= 1
            
            dismissal_animator!.fractionComplete = actualProgress
            
            if isDismissalSuccess {
                dismissal_animator!.stopAnimation(false)
                dismissal_animator!.addCompletion { [unowned self] (pos) in
                    switch pos {
                    case .end:
                        self.didSuccessfullyDragDownToDismiss()
                    default:
                        fatalError("Must finish dismissal at end!")
                    }
                }
                dismissal_animator!.finishAnimation(at: .end)
            }
            
        case .ended, .cancelled:
            
            shield_click_on_loading(isShield: false)
            
            if dismissal_animator == nil {
                // Gesture's too quick that it doesn't have dismissal_animator!
                print("Too quick there's no animator!")
                didCancelDismissalTransition()
                return
            }
            // NOTE:
            // If user lift fingers -> ended
            // If gesture.isEnabled -> cancelled
            
            // Ended, Animate back to start
            dismissal_animator!.pauseAnimation()
            dismissal_animator!.isReversed = true
            
            // Disable gesture until reverse closing animation finishes.
            gesture.isEnabled = false
            dismissal_animator!.addCompletion { [unowned self] (pos) in
                self.didCancelDismissalTransition()
                gesture.isEnabled = true
            }
            dismissal_animator!.startAnimation()
        default:
            fatalError("Impossible gesture state? \(gesture.state.rawValue)")
        }
    }
    
    
    func didSuccessfullyDragDownToDismiss(){
        
        headerView.isUserInteractionEnabled = false
        
        goback_previous_controller(animated: true)
        
    }
    
    
    func didCancelDismissalTransition() {
        // Clean up
        interactive_starting_point = nil
        dismissal_animator = nil
        dragging_down_to_dismiss = false
    }
    
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
}
